var ModuleUtil = {
  getProductOrderData: function (param) {
    var mode = param.mode;
    var self = this;
    if (mode === 'create') {
      return this.getProductOrderTemplate(param.templId).then(function (config) {
        return self.getBusniessData(param.businessId, config).then(function (orderData) {
          return {
            config: config,
            orderData: orderData
          };
        });
      });
    } else {
      var sysOrderNo = param.sysOrderNo;
      var self = this;
      return this.getProductOrderByOrderNo(sysOrderNo).then(function (orderData) {
        var templId = orderData.orderTemplateId;
        return self.getProductOrderTemplate(templId).then(function (config) {
          var productOrderData = new ProduceOrderData(config, {
            orderData: orderData,
            mode: mode
          });
          return {
            config: config,
            orderData: productOrderData
          };
        });
      });
    }
  },

  getProductOrderTemplate: function (templId, hasRes, applyId) {
    var postData, url;
    if (applyId === undefined) {
      url = 'createOrder/getTemplateById';
      postData = {
        id: templId
      };
    } else {
      url = 'createOrderApply/getTemplateById';
      postData = {
        apply_id: applyId
      };
    }

    return ajaxRequest(url, postData).then(function (data) {
      var configData = data.temp_info;
      configData = JSON.parse(configData);
      if (hasRes) {
        return configData;
      }
      var config = new ProduceOrderTemplConfigModel(configData);
      return config;
    });
  },

  getBusniessData: function (businessId, config) {
    var self = this;
    return this.getBusniessDataById(businessId).then(function (busRes) {
      var factoryNo = busRes.titleBean.factoryNo;
      return Promise.all([
        self.getBomData(factoryNo),
        SysUtil.getUser(),
        self.getSysOrderNo()
      ]).then(function (res) {
        var bomRes = res[0];
        var user = res[1];
        var sysOrderNo = res[2];
        var serialNo = bomRes.titleBean.serialNo;
        return self.getWasteRateList(serialNo).then(function (wasteRateList) {
          var productOrderData = new ProduceOrderData(config, {
            busRes: busRes,
            bomRes: bomRes,
            sysOrderNo: sysOrderNo,
            wasteRateList: wasteRateList,
            user: user,
            mode: 'create'
          });
          return productOrderData;
        });
      });
    });
  },

  getRefreshBusniessData: function (config, produceData) {
    var self = this;
    return Promise.all([
      this.getBusniessDataById(produceData.businessId),
      this.getBomData(produceData.factoryNo)
    ]).then(function (res) {
      var busRes = res[0];
      var bomRes = res[1];
      var serialNo = bomRes.titleBean.serialNo;
      return self.getWasteRateList(serialNo).then(function (wasteRateList) {
        var productOrderData = new ProduceOrderData(config, {
          busRes: busRes,
          bomRes: bomRes,
          sysOrderNo: produceData.sysOrderNo,
          wasteRateList: wasteRateList,
          user: {
            userName: produceData.createUser
          },
          mode: 'create',
          otherData: {
            approvalUser: produceData.approvalUser,
            proDept: produceData.proDept,
            businessId: produceData.businessId
          },
          produceRes:produceData
        });
        return productOrderData;
      });
    });
  },

  getBusniessDataById: function (businessId) {
    return ajaxRequest('createOrderForBomOrder/getBomOrderBussinessById', {
      id: businessId
    }).then(function (res) {
      return res;
    });
  },

  getBomData: function (factoryNo) {
    return ajaxRequest('createOrderForBomOrder/getBomOrderById', {
      fullFactoryNo: factoryNo,
      status: 1
    }).then(function (res) {
      return res;
    });
  },

  getWasteRateList: function (serialNo) {
    return ajaxRequest('createOrderForBomOrder/getWasteRateForBomSelf', {
      serialNo: serialNo
    }).then(function (wasteRateList) {
      return wasteRateList;
    });
  },

  getSysOrderNo: function () {
    return ajaxRequest('createOrder/getOrderInfoFixed').then(function (res) {
      var orderId = _.get(res, '[0].result', '');
      return orderId;
    });
  },

  getProductOrderByOrderNo: function (sysOrderNo) {
    return ajaxRequest('createOrderForBomOrder/getOrderBySysOrderNo', {
      sysOrderNo: sysOrderNo
    }).then(function (res) {
      return res;
    });
  },

  getProductOrderForApply: function (param) {
    var sysOrderNo = param.sysOrderNo;
    var mode = param.mode;
    var self = this;
    var applyId = param.applyId;
    return this.getProductOrderByOrderNo(sysOrderNo).then(function (orderData) {
      var templId = orderData.orderTemplateId;
      return self.getProductOrderTemplate(templId, true).then(function (configData) {
        var config = new ProduceOrderTemplConfigModel(configData);
        var productOrderData = new ProduceOrderData(config, {
          orderData: orderData,
          mode: mode
        });
        if (mode === 'applyUpdate') {
          var newConfig = new ProduceOrderTemplConfigModel(configData);
          var newProductOrderData = new ProduceOrderData(config, {
            orderData: orderData,
            mode: mode
          });
          return {
            config: config,
            orderData: productOrderData,
            newConfig: newConfig,
            newOrderData: newProductOrderData
          };
        }

        return self.getApplyProductOrder(sysOrderNo, applyId).then(function (newOrderData) {
          var newTemplId = newOrderData.orderTemplateId;
          return self.getProductOrderTemplate(newTemplId, true, applyId).then(function (newConfigData) {
            var newConfig = new ProduceOrderTemplConfigModel(newConfigData);
            var newProductOrderData = new ProduceOrderData(newConfig, {
              orderData: newOrderData,
              mode: mode
            });
            newProductOrderData.setCheckUpdate(productOrderData, newConfig);
            return {
              config: config,
              orderData: productOrderData,
              newConfig: newConfig,
              newOrderData: newProductOrderData
            };
          });
        });
      });
    });
  },

  getApplyProductOrder: function (sysOrderNo, applyId) {
    return ajaxRequest('createOrderForBomOrder/getApplyOrder', {
      sysOrderNo: sysOrderNo,
      applyId: applyId
    }).then(function (res) {
      return res;
    });
  },

  createProduceOrder: function (config, produceData, vm) {
    var self = this;
    vm.loadingText = '保存订单模板...';
    return this.saveTemplateConfig(config, produceData).then(function (templId) {
      vm.loadingText = '保存订单数据...';
      return self.saveProduceOrderData(produceData, templId);
    });
  },

  updateProduceOrder: function (config, produceData, vm) {
    var self = this;
    vm.loadingText = '修改订单模板...';
    return this.saveTemplateConfig(config, produceData).then(function (templId) {
      vm.loadingText = '修改订单数据...';
      return self.saveProduceOrderData(produceData, templId, undefined, true);
    });
  },

  approvalProduceOrder: function (produceData, data, vm) {
    var status = data.status;
    var self = this;
    if (status === 1) {
      vm.loadingText = '生产订单审核通过中...';
    } else if (status === -1) {
      vm.loadingText = '生产订单退回中...';
    } else {
      vm.loadingText = '生产订单计划中...';
    }
    return ajaxRequest('createOrder/updateAudit', {
      order_p_audit: status,
      order_p_order_no: produceData.sysOrderNo,
      order_p_product_no: produceData.factoryNo,
      audit_msg: data.remark
    }).then(function (msg) {
      if (status === 1) {
        vm.loadingText = '上传审核通过的订单图片...';
        return self.getProduceOrderImage(data.el, 'produceOrder').then(function (imgUrl) {
          return ajaxRequest('fileManager/uploadFileForPrint', {
            order_no: produceData.sysOrderNo,
            type: 1,
            file_name: produceData.sysOrderNo,
            url: imgUrl
          }).then(function () {
            return msg;
          });
        });
      }
      return msg;
    });
  },

  approvalApplyProduceOrder: function (produceData, data, vm) {
    var status = data.status;
    var self = this;
    if (status === 1) {
      vm.loadingText = '生产订单审核通过中...';
    } else {
      vm.loadingText = '生产订单退回中...';
    }
    return ajaxRequest('createOrderApply/saveAsAuditInfo', {
      apply_id: data.applyId,
      type: 1,
      order_no: produceData.sysOrderNo,
      order_p_product_no: produceData.factoryNo,
      status: status,
      remark: data.remark
    }).then(function (res) {
      if (res.msg !== '数据审核成功') {
        return msg;
      }
      if (status === 1) {
        vm.loadingText = '上传审核通过的订单图片...';
        return self.getProduceOrderImage(data.el, 'produceOrder').then(function (imgUrl) {
          return ajaxRequest('fileManager/uploadFileForPrint', {
            order_no: produceData.sysOrderNo,
            type: 1,
            file_name: produceData.sysOrderNo,
            url: imgUrl
          }).then(function () {
            return true;
          });
        });
      }
      return true;
    });
  },

  toApplyUpdateProduceOrder: function (config, produceData, option, vm) {
    var self = this;
    vm.loadingText = '获取申请id...';
    return this.getOrderApplyId().then(function (applyId) {
      vm.loadingText = '保存订单模板...';
      return self.saveTemplateConfig(config, produceData, applyId).then(function (templId) {
        vm.loadingText = '保存订单数据...';
        return self.saveProduceOrderData(produceData, templId, applyId).then(function () {
          vm.loadingText = '提交修改申请...';
          return self.applyUpdateProduceOrder(produceData, option, applyId).then(function (msg) {
            return msg;
          });
        });
      });
    });
  },

  applyUpdateProduceOrder: function (produceData, option, applyId) {
    var oldData = option.oldData;
    var specialRemark = oldData.getSpecialRemark(produceData);
    return ajaxRequest('createOrderApply/saveAsApplyInfo', {
      apply_id: applyId,
      order_no: produceData.sysOrderNo,
      order_p_product_no: produceData.factoryNo,
      type: 1,
      remark: option.remark,
      special_remark: specialRemark
    }).then(function (msg) {
      return msg;
    });
  },

  saveTemplateConfig: function (config, produceData, applyId) {
    var postData = config.getObject(produceData);
    if (applyId === undefined) {
      return ajaxRequest('createOrder/saveAsOrderTemplate', {
        type: 1,
        temp_name: 'produceTemplate',
        table_source_line_total: "BST",
        temp_info: JSON.stringify(postData)
      }).then(function (obj) {
        var id = obj.id;
        return id;
      });
    }
    return ajaxRequest('createOrderApply/saveAsOrderTemplate', {
      type: 1,
      apply_id: applyId,
      temp_name: 'produceApplyTemplate',
      table_source_line_total: "BST",
      temp_info: JSON.stringify(postData)
    }).then(function (obj) {
      var id = obj.id;
      return id;
    });
  },

  saveProduceOrderData: function (produceData, templId, applyId, hasUpdate) {
    if (applyId === undefined) {
      var postData = produceData.getObject();
      postData.orderTemplateId = templId;
      return ajaxRequest('createOrderForBomOrder/saveOrderByBomOrder', {
        dataStr: JSON.stringify(postData),
        action: hasUpdate ? 'update' : 'add'
      }).then(function () {
        return true;
      });
    }

    var postData = produceData.getObject('applyUpdate');
    postData.orderTemplateId = templId;
    postData.titleBean.applyId = applyId;
    return ajaxRequest('createOrderForBomOrder/saveOrderInfoForApply', {
      dataStr: JSON.stringify(postData)
    }).then(function () {
      return true;
    });
  },

  getOrderApplyId: function () {
    return ajaxRequest('createOrderApply/getOrderApplyId').then(function (res) {
      var applyId = res.result;
      return applyId;
    });
  },

  getProduceOrderImage: function (el, name) {
    if (!domtoimage) {
      return Promise.reject('domtoimage文件加载失败');
    }

    return new Promise(function (resole, reject) {
      domtoimage.toBlob(el, {
        bgcolor: '#ffffff',
        quality: 1
      }).then(function (blob) {
        var file = {
          name: name,
          blob: blob
        };
        return postImgsToQiniu('fileManager/getQiniuToken', file).then(function (imgUrl) {
          imgUrl = imgUrl[0];
          resole(imgUrl);
        });
      }).catch(function () {
        reject('html转换为图片失败');
      });
    });
  }
};
